﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Marmat.Template.WinForm
{
    /// <summary>
    /// 更新客户端的帮助类
    /// </summary>
    public class UpgradeClient : Marmat.Foundation.IUpgrade
    {

        /// <summary>
        /// 升级程序的程序名称,通常以.exe结尾
        /// </summary>
        public virtual string ApplicationName { get; set; } = "Updater.exe";

        /// <summary>
        /// 获取或设置更新系统需要所连接的服务器地址。
        /// </summary>
        public string Host { get; set; }

        /// <summary>
        /// 获取或设置更新完成后启动的主程序名称。
        /// </summary>
        public string StartupApplication { get; set; }

        /// <summary>
        /// 检查应用是否有更新。
        /// </summary>
        /// <returns></returns>
        public virtual bool CheckUpgrade()
        {
            bool result = false;
            string path = System.IO.Path.Combine(Application.StartupPath, this.ApplicationName);
            string new_path = System.IO.Path.Combine(Application.StartupPath, "New" + this.ApplicationName);
            if (System.IO.File.Exists(new_path))
            {
                System.IO.File.Delete(path);
                System.IO.File.Move(new_path, path);
            }
            if (System.IO.File.Exists(path))
            {
                Assembly assembly = System.Reflection.Assembly.LoadFile(path);
                Type type = assembly.GetTypes().FirstOrDefault(item => item.Name == "Upgrade");
                if (type != null)
                {
                    object client = assembly.CreateInstance(type.FullName, true);
                    type = client.GetType();
                    type.GetProperty("Host").SetValue(client, this.Host);
                    type.GetProperty("StartupApplication").SetValue(client, this.StartupApplication);
                    MethodInfo methodInfo = type.GetMethod("CheckUpdate");
                    result = (bool)methodInfo.Invoke(client, null);
                }
            }
            return result;
        }

        /// <summary>
        /// 升级应用。
        /// </summary>
        public virtual void Upgrade()
        {
            string path = System.IO.Path.Combine(Application.StartupPath, this.ApplicationName);
            if (System.IO.File.Exists(path))
            {
                Application.ExitThread();
                Process.Start(path);
            }
        }
    }
}
